package sanmubird.scratch.y210914;

import com.google.common.collect.Sets;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author sam
 * @date 2021/9/14 20:02
 */
public class Dispatch {

    private final Set<Task> taskSet;

    private final Set<Person> workerSet;

    private final Set<Person> fullTaskWorkerSet;

    private final Set<Person> leakTaskWorkerSet;


    public Dispatch(Collection<Task> taskSet, Collection<Person> workerSet) {
        this.taskSet = Sets.newHashSet(taskSet);
        this.workerSet = Sets.newHashSet(workerSet);
        this.fullTaskWorkerSet = Sets.newHashSet();
        this.leakTaskWorkerSet = Sets.newHashSet(workerSet);
    }


    public void assign(Task task) {
        if (this.leakTaskWorkerSet.isEmpty()) {
            return;
        }
        Task.Tag tag = task.getMaxOrderTag();
        Map<TypeEnum, Person> map = this.leakTaskWorkerSet.stream().collect(Collectors.toMap(p -> p.getMaxPriorityPreference().getType(), Function.identity(), (p1, p2) -> p1));
        Person person = map.computeIfAbsent(
                tag.getType()
                , typeEnum -> this.leakTaskWorkerSet.iterator().next()
        );
        person.getTodoList().add(task);
        if (person.isFullTsk()) {
            this.fullTaskWorkerSet.add(person);
            this.leakTaskWorkerSet.remove(person);
        }
    }


    public void main() {
        Queue<Task> taskQueue = new LinkedList<>(this.taskSet);
        // 任务全分配了 或 人都分配满活了
        while (taskQueue.size() > 0 && this.leakTaskWorkerSet.size() > 0) {
            Task task = taskQueue.poll();
            if (Objects.nonNull(task)) {
                assign(task);
            }
        }

        System.out.println("=================== taskQueue  =====================");
        taskQueue.forEach(System.out::println);
        System.out.println("====================  workerSet ====================");
        this.workerSet.forEach(System.out::println);
        System.out.println("================== fullTaskWorkerSet  ======================");
        this.fullTaskWorkerSet.forEach(System.out::println);
        System.out.println("=================== leakTaskWorkerSet  =====================");
        this.leakTaskWorkerSet.forEach(System.out::println);
    }
}
